class Mobile::Weixin::WeixinController < ApplicationController
    before_action :weixin_client
    before_action :invoke_wx_auth
    before_action :get_wechat_sns
    before_action :get_current_user
    before_action :get_current_restaurant,except: [:welcome]
    before_action :cors_set_access_control_headers

    def welcome
        @restaurant = Restaurant.find params[:restaurant_id]
        @table_no = params[:table_no]
        render layout: false
    end    

    def cors_set_access_control_headers
        headers['Access-Control-Allow-Origin'] = '*'
        headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
        headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
        headers['Access-Control-Max-Age'] = "1728000"
    end


    def weixin_client
        if !$client 
            $client = WeixinAuthorize::Client.new(WEIXIN_APPID, WEIXIN_APPSECRET)
        end 
    end 

    def get_current_user
        @current_user = User.find_by_open_id(session[:open_id])       
    end    

    def get_current_restaurant
        @restaurant = Restaurant.find params[:restaurant_id]
        @car = Car.find_or_create_by(user_id: @current_user.id,restaurant_id:@restaurant.id)
    end    

    private
    def invoke_wx_auth
        user = User.first
        if user.present?
            session[:open_id] = user.open_id
        end  
          
        # reset_session     
        # puts session[:open_id]   

        if params[:state].present? || session[:open_id].present? 
            return 
        end         
        # 生成授权url，再进行跳转
        sns_url =  $client.authorize_url(request.url,scope="snsapi_base")
        Rails.logger.info("share: #{request.url} && #{sns_url}")
        redirect_to sns_url and return
    end

    def get_wechat_sns
        if  session[:open_id].blank? && params[:state].present?
          sns_info = $client.get_oauth_access_token(params[:code])
          Rails.logger.info("Weixin oauth2 response: #{sns_info.result}")
          # 重复使用相同一个code调用时：
          if sns_info.result["errcode"] != "40029"
            session[:open_id] = sns_info.result["openid"]
            oauth_token = sns_info.result["access_token"]
            update_user(oauth_token)
          end
        end
    end

    def update_user oauth_token
        user = User.find_by_open_id session[:open_id]       
        # user_info = $client.get_oauth_userinfo(session[:open_id],oauth_token,lang="zh_CN")      
        # Rails.logger.debug("Weixin User info response: #{user_info.result}")
        if user.blank?
            user = User.new
        end 
        # user.nick_name = user_info.result["nickname"]
        # user.header_img_url = user_info.result["headimgurl"]
        user.open_id = session[:open_id]
        user.save
    end 



end
